package tgc.rj.garbage;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import tgc.rj.garbage.utlis.AisleUtils;
import tgc.rj.garbage.utlis.FilesUtils;
import tgc.rj.garbage.utlis.Queue;

public class PushActivity extends AppCompatActivity implements Runnable {

    private TextView tv_txt, tv_num, xtsz;
    private Boolean flag = true;
    private TextView push_return;
    private String user;
    public SharedPreferences sz;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_push);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        user = bundle.getString("user");
        sz = this.getSharedPreferences("jcsz", MODE_PRIVATE);
        xtsz = findViewById(R.id.xtsz);
        xtsz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PushActivity.this, SettingActivity.class);
                startActivity(intent);
            }
        });
        tv_txt = findViewById(R.id.tv_txt);
        tv_num = findViewById(R.id.tv_num);
        push_return = findViewById(R.id.push_return);
        push_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        getStr();
    }

    /***
     * 开启上货线程
     */
    @Override
    public void run() {
        String oldCode = "";
        Queue.empty();
        while (flag) {
            String s = Queue.pop();
            if (s != null && !s.equals(oldCode)) {
                Message message = new Message();
                Bundle bundle = new Bundle();
                if (sendHttp(user, s) == true) {
                    Integer num = AisleUtils.push(s);
                    oldCode = s;
                    if (num == -1) {
                        bundle.putString("data", "货道已满！");
                        message.setData(bundle);
                        this.handler1.sendMessage(message);
                    } else {
                        bundle.putString("data", "该垃圾袋编号为：" + s + "，请放入第 " + num + " 货道。");
                        message.setData(bundle);
                        this.handler1.sendMessage(message);
                    }
                }
            }
        }
    }

    /***
     * 上货货道提示
     */
    private Handler handler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String num = msg.getData().getString("data");
            getStr();
            tv_num.setText(num);
        }
    };

    @Override
    protected void onPause() {
        flag = false;
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //扫一次重启一次线程
        new Thread(this).start();
    }

    public void getStr() {
        String str = "";
        for (int i = 0; i < 60; i++) {
            int size = AisleUtils.gd.get(i).size();
            str += "[" + (i < 9 ? "0" : "") + (i + 1) + "货道:" + size + "]" + " ";
            if ((i + 1) % 10 == 0) {
                str += "\n\n\n";
            }
        }
        tv_txt.setText(str);
    }

    /***
     * 发送上货记录
     * 请求名：weixin/ydyshjl
     * @param user 引导员openId
     * @param ljdbh 垃圾袋编号
     * @return
     */
    private Boolean sendHttp(final String user, final String ljdbh) {
        final String jqbh = sz.getString("name", "");
        Boolean A = true;
        if (jqbh.equals("") || jqbh == null) {
            A = false;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tv_num.setText("该机器未设置编号，先设置机器编号再进行上货！");
                }
            });
        }
        if (A) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    HttpURLConnection conn = null;
                    final String urls = sz.getString("url", "https://baiyao.51baiyao.com");
                    final String urlStr = urls + "/gsm/weixin/ydyshjl";
                    try {
                        URL url = new URL(urlStr);
                        conn = (HttpURLConnection) url.openConnection();
                        conn.setConnectTimeout(8000);
                        conn.setReadTimeout(8000);
                        conn.setDoOutput(true);
                        conn.setDoInput(true);
                        conn.setUseCaches(false);
                        conn.setRequestProperty("Charset", "UTF-8");
                        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                        conn.setRequestMethod("POST");
                        String jqbhStr = URLEncoder.encode(jqbh, "UTF-8");
                        final String paramStr = "openId=" + user.trim() + "&ljdbh=" + ljdbh + "&jqbh=" +jqbhStr ;
                        OutputStream out = conn.getOutputStream();
                        DataOutputStream dataOut = new DataOutputStream(out);
                        dataOut.writeBytes(paramStr);
                        dataOut.flush();
                        dataOut.close();
                        InputStream inputStream = conn.getInputStream();
                        final String reponse = FilesUtils.readInfo(inputStream);
                        runOnUiThread(new Runnable() {
                            public void run() {

                            }
                        });
                        if (conn != null) {
                            conn.disconnect();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        return A;
    }
}